/**
 * 全局状态管理
 * 
 * 使用Zustand管理应用的全局状态
 */

import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { 
  UserInfo, 
  AppSettings, 
  Notification, 
  ThemeMode,
  DataSourceConfig,
  ApiDefinition,
  ComponentHealth,
  SystemMetrics,
  PluginInfo
} from '@/types';

// ============================================================================
// 用户状态管理
// ============================================================================

interface UserState {
  /** 当前用户信息 */
  user: UserInfo | null;
  /** 是否已登录 */
  isAuthenticated: boolean;
  /** 登录令牌 */
  token: string | null;
  
  /** 设置用户信息 */
  setUser: (user: UserInfo) => void;
  /** 设置登录令牌 */
  setToken: (token: string) => void;
  /** 登出 */
  logout: () => void;
}

export const useUserStore = create<UserState>()(
  persist(
    (set) => ({
      user: null,
      isAuthenticated: false,
      token: null,
      
      setUser: (user) => set({ user, isAuthenticated: true }),
      setToken: (token) => set({ token }),
      logout: () => set({ user: null, isAuthenticated: false, token: null }),
    }),
    {
      name: 'user-storage',
      storage: createJSONStorage(() => localStorage),
    }
  )
);

// ============================================================================
// 应用设置状态管理
// ============================================================================

interface SettingsState extends AppSettings {
  /** 更新设置 */
  updateSettings: (settings: Partial<AppSettings>) => void;
  /** 切换主题 */
  toggleTheme: () => void;
  /** 切换侧边栏 */
  toggleSidebar: () => void;
}

export const useSettingsStore = create<SettingsState>()(
  persist(
    (set, get) => ({
      theme: 'system' as ThemeMode,
      language: 'zh-CN',
      sidebarCollapsed: false,
      autoRefreshInterval: 30,
      showDebugInfo: false,
      
      updateSettings: (settings) => set((state) => ({ ...state, ...settings })),
      toggleTheme: () => {
        const currentTheme = get().theme;
        const nextTheme = currentTheme === 'light' ? 'dark' : 'light';
        set({ theme: nextTheme });
      },
      toggleSidebar: () => set((state) => ({ sidebarCollapsed: !state.sidebarCollapsed })),
    }),
    {
      name: 'settings-storage',
      storage: createJSONStorage(() => localStorage),
    }
  )
);

// ============================================================================
// 通知状态管理
// ============================================================================

interface NotificationState {
  /** 通知列表 */
  notifications: Notification[];
  
  /** 添加通知 */
  addNotification: (notification: Omit<Notification, 'id' | 'createdAt'>) => void;
  /** 移除通知 */
  removeNotification: (id: string) => void;
  /** 清空所有通知 */
  clearNotifications: () => void;
}

export const useNotificationStore = create<NotificationState>((set) => ({
  notifications: [],
  
  addNotification: (notification) => {
    const newNotification: Notification = {
      ...notification,
      id: Date.now().toString(),
      createdAt: Date.now(),
    };
    
    set((state) => ({
      notifications: [...state.notifications, newNotification],
    }));
    
    // 自动移除通知
    if (notification.autoClose !== false) {
      const duration = notification.duration || 5000;
      setTimeout(() => {
        set((state) => ({
          notifications: state.notifications.filter(n => n.id !== newNotification.id),
        }));
      }, duration);
    }
  },
  
  removeNotification: (id) => set((state) => ({
    notifications: state.notifications.filter(n => n.id !== id),
  })),
  
  clearNotifications: () => set({ notifications: [] }),
}));

// ============================================================================
// 数据源状态管理
// ============================================================================

interface DataSourceState {
  /** 数据源列表 */
  dataSources: DataSourceConfig[];
  /** 当前选中的数据源 */
  selectedDataSource: DataSourceConfig | null;
  /** 加载状态 */
  loading: boolean;
  /** 错误信息 */
  error: string | null;
  
  /** 设置数据源列表 */
  setDataSources: (dataSources: DataSourceConfig[]) => void;
  /** 添加数据源 */
  addDataSource: (dataSource: DataSourceConfig) => void;
  /** 更新数据源 */
  updateDataSource: (id: string, dataSource: Partial<DataSourceConfig>) => void;
  /** 删除数据源 */
  removeDataSource: (id: string) => void;
  /** 选择数据源 */
  selectDataSource: (dataSource: DataSourceConfig | null) => void;
  /** 设置加载状态 */
  setLoading: (loading: boolean) => void;
  /** 设置错误信息 */
  setError: (error: string | null) => void;
}

export const useDataSourceStore = create<DataSourceState>((set) => ({
  dataSources: [],
  selectedDataSource: null,
  loading: false,
  error: null,
  
  setDataSources: (dataSources) => set({ dataSources }),
  addDataSource: (dataSource) => set((state) => ({
    dataSources: [...state.dataSources, dataSource],
  })),
  updateDataSource: (id, updates) => set((state) => ({
    dataSources: state.dataSources.map(ds => 
      ds.id === id ? { ...ds, ...updates } : ds
    ),
  })),
  removeDataSource: (id) => set((state) => ({
    dataSources: state.dataSources.filter(ds => ds.id !== id),
    selectedDataSource: state.selectedDataSource?.id === id ? null : state.selectedDataSource,
  })),
  selectDataSource: (dataSource) => set({ selectedDataSource: dataSource }),
  setLoading: (loading) => set({ loading }),
  setError: (error) => set({ error }),
}));

// ============================================================================
// API状态管理
// ============================================================================

interface ApiState {
  /** API列表 */
  apis: ApiDefinition[];
  /** 当前选中的API */
  selectedApi: ApiDefinition | null;
  /** 加载状态 */
  loading: boolean;
  /** 错误信息 */
  error: string | null;
  
  /** 设置API列表 */
  setApis: (apis: ApiDefinition[]) => void;
  /** 添加API */
  addApi: (api: ApiDefinition) => void;
  /** 更新API */
  updateApi: (id: string, api: Partial<ApiDefinition>) => void;
  /** 删除API */
  removeApi: (id: string) => void;
  /** 选择API */
  selectApi: (api: ApiDefinition | null) => void;
  /** 设置加载状态 */
  setLoading: (loading: boolean) => void;
  /** 设置错误信息 */
  setError: (error: string | null) => void;
}

export const useApiStore = create<ApiState>((set) => ({
  apis: [],
  selectedApi: null,
  loading: false,
  error: null,
  
  setApis: (apis) => set({ apis }),
  addApi: (api) => set((state) => ({
    apis: [...state.apis, api],
  })),
  updateApi: (id, updates) => set((state) => ({
    apis: state.apis.map(api => 
      api.id === id ? { ...api, ...updates } : api
    ),
  })),
  removeApi: (id) => set((state) => ({
    apis: state.apis.filter(api => api.id !== id),
    selectedApi: state.selectedApi?.id === id ? null : state.selectedApi,
  })),
  selectApi: (api) => set({ selectedApi: api }),
  setLoading: (loading) => set({ loading }),
  setError: (error) => set({ error }),
}));

// ============================================================================
// 监控状态管理
// ============================================================================

interface MonitoringState {
  /** 系统指标 */
  systemMetrics: SystemMetrics | null;
  /** 组件健康状态 */
  componentHealth: ComponentHealth[];
  /** 最后更新时间 */
  lastUpdated: number | null;
  /** 自动刷新定时器ID */
  refreshTimer: NodeJS.Timeout | null;
  
  /** 设置系统指标 */
  setSystemMetrics: (metrics: SystemMetrics) => void;
  /** 设置组件健康状态 */
  setComponentHealth: (health: ComponentHealth[]) => void;
  /** 开始自动刷新 */
  startAutoRefresh: (interval: number, callback: () => void) => void;
  /** 停止自动刷新 */
  stopAutoRefresh: () => void;
}

export const useMonitoringStore = create<MonitoringState>((set, get) => ({
  systemMetrics: null,
  componentHealth: [],
  lastUpdated: null,
  refreshTimer: null,
  
  setSystemMetrics: (metrics) => set({ 
    systemMetrics: metrics, 
    lastUpdated: Date.now() 
  }),
  setComponentHealth: (health) => set({ 
    componentHealth: health, 
    lastUpdated: Date.now() 
  }),
  startAutoRefresh: (interval, callback) => {
    const { refreshTimer } = get();
    if (refreshTimer) {
      clearInterval(refreshTimer);
    }
    
    const timer = setInterval(callback, interval * 1000);
    set({ refreshTimer: timer });
  },
  stopAutoRefresh: () => {
    const { refreshTimer } = get();
    if (refreshTimer) {
      clearInterval(refreshTimer);
      set({ refreshTimer: null });
    }
  },
}));

// ============================================================================
// 插件状态管理
// ============================================================================

interface PluginState {
  /** 插件列表 */
  plugins: PluginInfo[];
  /** 加载状态 */
  loading: boolean;
  /** 错误信息 */
  error: string | null;
  
  /** 设置插件列表 */
  setPlugins: (plugins: PluginInfo[]) => void;
  /** 更新插件状态 */
  updatePluginStatus: (id: string, status: PluginInfo['status']) => void;
  /** 设置加载状态 */
  setLoading: (loading: boolean) => void;
  /** 设置错误信息 */
  setError: (error: string | null) => void;
}

export const usePluginStore = create<PluginState>((set) => ({
  plugins: [],
  loading: false,
  error: null,
  
  setPlugins: (plugins) => set({ plugins }),
  updatePluginStatus: (id, status) => set((state) => ({
    plugins: state.plugins.map(plugin => 
      plugin.id === id ? { ...plugin, status } : plugin
    ),
  })),
  setLoading: (loading) => set({ loading }),
  setError: (error) => set({ error }),
}));
